package com.grape.juc.safe.communication;
/**
 * 描述:多线程通讯
 * @author: myx
 * @date: 2019-05-08
 * Copyright © 2019-grape. All rights reserved.
 */
public class CommunicationTest{
	public static void main(String[] args) {
		Res res = new Res();
		//数据发生错乱，造成线程安全问题
//		IntThrad intThrad = new IntThrad(res);
//		OutThread outThread = new OutThread(res);

		IntThradSolve intThrad = new IntThradSolve(res);
		OutThradSlove outThread = new OutThradSlove(res);
		intThrad.start();
		outThread.start();
	}
}

/**
 * 共享对象
 */
class Res {
	public String userSex;
	public String userName;
}


/**
 * 写线程(存在问题)
 */
class IntThrad extends Thread {
	private Res res;

	public IntThrad(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			if (count == 0) {
				res.userName = "沐宇熙";
				res.userSex = "男";
			} else {
				res.userName = "小紅";
				res.userSex = "女";
			}
			count = (count + 1) % 2;
		}
	}
}

/**
 * 读线程(存在问题)
 */
class OutThread extends Thread {
	private Res res;

	public OutThread(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			System.out.println(res.userName + "--" + res.userSex);
		}
	}
}

/**
 * 写线程(解决问题)
 */
class IntThradSolve extends Thread {
	private Res res;

	public IntThradSolve(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			//
			synchronized (res) {
				if (count == 0) {
					res.userName = "沐宇熙";
					res.userSex = "男";
				} else {
					res.userName = "小紅";
					res.userSex = "女";
				}
				count = (count + 1) % 2;
			}

		}
	}
}

/**
 * 读线程(解决问题)
 */
class OutThradSlove extends Thread {
	private Res res;

	public OutThradSlove(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			//读线程为什么也要加上synchronized关键字:
			//由于读写同时进行有可能写操作只写出了res.userName，在写res.userSex时写操作吧res.userSex改变了，写出来的值就不正确了
			synchronized (res) {
				System.out.println(res.userName + "," + res.userSex);
			}
		}

	}
}


